<template>
  <div class="PostDetail">
    <div class="postDetail-container">
      <!-- 左侧操作栏 -->
      <div class="postDetail-actions">
        <div class="action-item comment" @click="handleComment">
          <el-icon>
            <ChatDotRound />
          </el-icon>
          <span class="action-text">评论</span>
        </div>
        <div class="action-item collect" @click="handleCollect">
          <el-icon>
            <Star />
          </el-icon>
          <span class="action-text">收藏</span>
        </div>
        <div class="action-item like" @click="handleLike">
          <el-icon>
            <Pointer />
          </el-icon>
          <span class="action-text">点赞</span>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="postDetail-main">
        <div class="postDetail-content">
          <div v-if="loading" class="loading-state">加载中...</div>
          <div v-else-if="postDetailItem" class="post-content">
            <div class="post-header">
              <h1 class="post-title">{{ postDetailItem.title }}</h1>
              <div class="post-meta">
                发布时间 <span class="post-time">{{ formatDate(postDetailItem.createTime) }}</span>
              </div>
            </div>

            <div class="post-body">
              <div class="post-text" @click="showImagePreview(getContentImages(postDetailItem.content), $event)"
                v-html="postDetailItem.content"></div>
            </div>
          </div>
          <div v-else class="empty-state">暂无数据</div>
          <div class="report-container">
            <div class="report">
              举报
            </div>
          </div>
        </div>


        <!-- 评论区域 -->
        <div class="comment-body">
          <div class="comment-header">
            <div class="header-title">
              <div class="title-left">
                <div class="all-comment">
                  全部评论
                </div>
                <div class="Only-look-up">
                  只看楼主
                </div>
              </div>
              <div class="title-right">
                <div class="default">
                  默认
                </div>
                <div class="up-to-date">
                  最新
                </div>
              </div>
            </div>
          </div>
          <div class="comment-centent">
            <div class="create-comment">
              <form @submit.prevent="submitComment">

                <!-- 富文本框 -->
                <div class="comment-input">
                  <Editor ref="editorRef" v-model="commentText" height="150px" />
                </div>
                <div class="editor-actions">
                  <div class="action-icons">
                    <div class="action-list">
                      <span class="mention-icon">@</span>

                      <!-- 添加表情选择器 -->
                      <Emoji trigger="click" @emoji-selected="handleEmoji" />
                    </div>
                    <el-button @click="cerateCommnet" type="primary" size="small" native-type="submit"
                      :disabled="!commentText.trim()">
                      发布
                    </el-button>
                  </div>
                </div>
              </form>
            </div>

            <!-- 添加无评论时的显示 -->
            <div v-if="commentList.length === 0" class="empty-comments">
              <el-empty description="暂无评论" :image-size="100"></el-empty>
            </div>
            <div v-else class="comment-list" v-for="(item, index) in commentList" :key="index">
              <div class="comment-item">
                <div class="user-info">
                  <el-avatar :size="40" :src="item.user.avatar" />
                  <div class="user-meta">
                    <span class="username">{{ item.user.username }}</span>
                    <span class="comment-time">{{ formatDate(item.commentTime) }}</span>
                  </div>
                </div>
                <div class="comment-text">
                  <div class="comment-html" @click="showImagePreview(getContentImages(item.content), $event)"
                    v-html="item.content"></div>
                </div>
                <div class="comment-actions">
                  <el-button text size="small">回复</el-button>
                  <el-button text size="small">点赞</el-button>
                </div>
                <div class="text" @click="toggleReply(index)" v-if="item.children && item.children.length > 0">
                  <el-icon>
                    <DArrowRight />
                  </el-icon>
                  <span>查看更多回复({{ item.children.length }})</span>
                </div>

                <!-- 回复列表 -->
                <div class="reply-list" v-if="showReply[index]">
                  <div class="reply-item" v-for="(reply, i) in item.children" :key="i">
                    <div class="reply-user">
                      <el-avatar :size="32" :src="reply.user.avatar" />
                      <span class="username">{{ reply.user.username }}</span>
                    </div>
                    <div class="reply-content">
                      <p>{{ reply.content }}</p>
                      <div class="reply-time">{{ formatDate(reply.commentTime) }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- <LoadMoreTrigger @loadMore="loadMore" text="正在加载更多评论..." /> -->
        </div>
      </div>

      <!-- 右侧用户信息 -->
      <div class="postDetail-sidebar" v-if="postDetailItem?.userInfo">
        <div class="user-card">
          <div class="user-card-info">
            <div class="user-card-avatar">
              <img :src="postDetailItem.userInfo.avatar" alt="用户头像">
            </div>
            <div class="user-info-item">
              <div class="card-username">{{ postDetailItem.userInfo.username }}</div>
              <!-- 粉丝和关注 -->
              <div class="fans-attention">
                <div class="fans">粉丝:<span class="number">0</span></div>
                <div class="attention-quantity">关注:<span class="number">0</span></div>
              </div>
            </div>
          </div>
          <div class="card-btn">
            <el-button class="card-button" type="primary" size="small">+关注</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <template>
    <el-image-viewer v-if="previewVisible" :url-list="previewImages" v-model:initial-index="previewIndex"
      @close="previewVisible = false" teleported :z-index="2000" />
  </template>
</template>

<script setup>
import { onMounted, ref, onUnmounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import service from '@/utils/request'
import { formatDate } from '@/utils/date' // 添加这行导入
import { ChatDotRound, Star, Pointer, Picture, DArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import LoadMoreTrigger from '@/components/LoadMoreTrigger.vue'
import Editor from '@/components/Editor.vue'
import Emoji from '@/components/Emoji.vue'
import { ElImageViewer } from 'element-plus'


// 定义组件
const editorRef = ref(null) // 引用编辑器实例
const route = useRoute()
const postDetailItem = ref(null)
const loading = ref(false) // 添加加载状态
const commentList = ref([])
const showReply = ref({}) //显示回复
const commentCount = ref(0)
const onlyShowAuthor = ref(false)
const sortType = ref('default')
const commentText = ref('')
const filteredComments = ref([])
const previewImages = ref([])
const previewVisible = ref(false)
const previewIndex = ref(0)
const userInfo = ref({
  id: ''
})


const handleEmoji = (emoji) => {
  if (editorRef.value) {
    editorRef.value.insertText(emoji + ' ')  // 使用组件暴露的方法
  }
}

const getPostDetail = async (id) => {
  loading.value = true
  try {
    const res = await service.get(`/posts/postId=${id}`)
    postDetailItem.value = res.data
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 在获取评论列表后，确保数据结构正确
const getCommentList = async (id) => {
  const res = await service.get(`/comments/posts=${id}`)
  if (res.code === 200) {
    commentList.value = res.data.map(item => ({
      ...item,
      children: item.children || [] // 确保children存在
    }))
  }
  console.log(res);

}

const cerateCommnet = async () => {
  if (!commentText.value.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }

  try {
    const postId = route.params.id

    const data = {
      userId: userInfo.value.id,
      content: commentText.value
    }
    const res = await service.post(`/posts/${postId}/comments`, data)

    if (res.code === 200) {
      ElMessage.success('评论成功')
      commentText.value = '' // 清空输入框
      await getCommentList(postId) // 刷新评论列表

    } else {
      ElMessage.error(res.message || '评论失败')
    }
  } catch (error) {
    console.error('评论出错:', error)
    ElMessage.error('评论出错，请稍后再试')
  }
}

onMounted(() => {
  const postId = route.params.id
  getPostDetail(postId)
  getCommentList(postId)
  const storedUser = JSON.parse(localStorage.getItem('userInfo')) || {}
  userInfo.value = {
    id: storedUser.id
  }
})

// 添加新方法
const handleComment = () => {
  // 评论逻辑
}

const handleCollect = () => {
  // 收藏逻辑
}

const handleLike = () => {
  // 点赞逻辑
}

// 新增内容图片解析方法
const getContentImages = (html) => {
  if (!html) return []
  const parser = new DOMParser()
  const doc = parser.parseFromString(html, 'text/html')
  return Array.from(doc.querySelectorAll('.custom-image-wrapper img')).map(img => img.src)
}

// 图片预览方法
const showImagePreview = (images, event) => {
  if (!event?.target) return

  // 获取实际点击的图片元素
  const clickedImg = event.target.closest('img')
  if (!clickedImg) return

  // 获取所有图片集合
  const parentNode = event.currentTarget
  const allImages = Array.from(parentNode.querySelectorAll('img'))

  // 查找当前点击图片的索引
  const currentIndex = allImages.findIndex(img => img.src === clickedImg.src)
  


  previewImages.value = allImages.map(img => img.src)
  previewIndex.value = currentIndex > -1 ? currentIndex : 0
  previewVisible.value = true
}


const submitComment = () => {
  // 提交评论逻辑
}
</script>


<style lang="scss" scoped>
@import "@/assets/css/PostDetail.scss";
</style>